import torch
import os
import numpy as np
import random
import copy


def seed_everything(seed=42):
    torch.manual_seed(seed)
    torch.cuda.manual_seed(seed)
    torch.cuda.manual_seed_all(seed)
    torch.backends.cudnn.deterministic = True
    torch.backends.cudnn.benchmark = False
    np.random.seed(seed)
    random.seed(seed)

def add_to_config(config, new_dict):
    values = []
    for key in new_dict.keys():
        try:
            value = getattr(new_dict, key)
        except AttributeError:
            value = new_dict[key]
        if isinstance(value, dict):
            for k, v in value.items():
                values.append(f"{k}_{v}")
        else:
            values.append(str(value))
        if key not in config.keys():
            raise ValueError(f"Invalid hyperparameter {key}. Valid hyperparameters are {config.keys()}")
        config[key] = copy.deepcopy(value)
    config.model_save_dir = os.path.join(config.log_dir, "-".join(values).replace("/", "_"), "models")
    
    return config
